﻿using System;
using System.Web.Security;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MyBBS.Data.Interfaces;
using System.Security.Cryptography;
using MyBBS.Data.SqlServer;

namespace MyBBS.Data
{
    public class UserRepository : IUserRepository
    {
        private PostDataContext _db;
        private readonly MembershipProvider membership = Membership.Provider;

        //public UserRepository()
        //    : this(new MyBBS.Data.SqlServer.PostDataContext())
        //{
        //}

        public UserRepository(PostDataContext db)
        {
            _db = db;
            if (_db == null)
                throw new InvalidOperationException("DataContext should not be null");
        }

        #region IUserRepository Members

        /// <summary>
        /// Validate the user, if ture, set authenticated cookie
        /// </summary>
        /// <param name="userName">User Name</param>
        /// <param name="password">Password</param>
        /// <returns>true, if validated</returns>
        public bool Login(string userName, string password)
        {
            if (membership.ValidateUser(userName, password))
            {
                FormsAuthentication.SetAuthCookie(userName, false);
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// Sign up a new user
        /// </summary>
        /// <param name="user">User</param>
        /// <returns>MembershipCreateStatus</returns>
        public MembershipCreateStatus SignUp(MyBBS.Data.Models.User user)
        {
            MembershipCreateStatus status;
            var _user = membership.CreateUser(user.UserName, user.Password, user.Email, null, null, true, null, out status);
            if (status == MembershipCreateStatus.Success)
            {
                FormsAuthentication.SetAuthCookie(_user.UserName, false);
            }
            return status;
        }

        /// <summary>
        /// Send the new password to the user via email, if the email exited
        /// </summary>
        /// <param name="email">Email address</param>
        public void SendPassword(string email)
        {
            
        }

        public void Logout()
        {
            FormsAuthentication.SignOut();
        }

        public Models.User GetUserByUserName(string userName)
        {
            var user = _db.Users.SingleOrDefault(u => u.UserName == userName);
            if (user == null)
            {
                throw new InvalidOperationException("Specified user doesn't exist");
            }

            return new Models.User { ID = user.UserId, UserName = user.UserName };
        }

        
        #endregion
    }
}
